<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>条件渲染</title>
	</head>
	<body>
		<div id="root"></div>

		<script
			type="text/javascript"
			src="./components/react.development.js"
		></script>
		<script
			type="text/javascript"
			src="./components/react-dom.development.js"
		></script>
		<script type="text/javascript" src="./components/babel.min.js"></script>

		<script type="text/babel">
      // 条件渲染   运算符if 或者 条件运算符 
      function UserGreeting (props) {
        return <h1>Welcome back!</h1>
      }

      function GuestGreeting (props) {
        return <h1>Please sign up.</h1>
      }
      
      function Greeting (props) {
        const isLoggedIn = props.isLoggedIn;
        if (isLoggedIn) {
          return <UserGreeting />;
        } else {
          return <GuestGreeting />;
        }
      }
      
      // ReactDOM.render(
      //   // 根据 isLoggedIn 的值来渲染不同的问候语
      //   <Greeting isLoggedIn={false} />,
      //   document.getElementById('root')
      // )

      // 通过变量来缓存并且绑定相应事件
      function LoginButton (props) {
        return (
          <button onClick={props.onClick}>Login</button>
        )
      }

      function LogoutButton (props) {
        return (
          <button onClick={props.onClick}>Logout</button>
        )
      }

      class LoginControl extends React.Component {
        constructor (props) {
          super(props);
          this.handleLoginClick = this.handleLoginClick.bind(this);
          this.handleLogoutClick = this.handleLogoutClick.bind(this);
          this.state = {isLoggedIn: false};
        }

        handleLoginClick () {
          this.setState({isLoggedIn: true})
        }

        handleLogoutClick () {
          this.setState({isLoggedIn: false})
        }

        render () {
          const isLoggedIn = this.state.isLoggedIn;
          let button;
          if (!isLoggedIn) {
            button = <LoginButton onClick={this.handleLoginClick} />
          } else {
            button = <LogoutButton onClick={this.handleLogoutClick} />
          }

          return (
            <div>
              <Greeting isLoggedIn={isLoggedIn}/>
              {button}
            </div>
          )
        }
      }

      ReactDOM.render(
        <LoginControl />,
        document.getElementById('root')
      )

		</script>
	</body>
</html>
